﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Data;
using ChuanYe.DAL;
using ChuanYe.Models;
using System.Threading.Tasks;
using ChuanYe.Commom;
using ChuanYe.Utils;
using Microsoft.AspNet.SignalR.Hubs;
using SJPlatForm.Web.Models;
using SJPlatForm.Web.Controllers;
using ChuanYe.Models.Model;

namespace SJPlatForm.Web
{
    public class FireDisposalChatHub : Hub
    {
        protected readonly FireInfoDAL dal = new FireInfoDAL();
        protected readonly UsersInfosDAL userinfoDAL = new UsersInfosDAL();

        public void Test(string message)

        {
            Clients.All.sendMessage("1", message);
        }

        public void SendText(string type, int fid, int userid, string message)
        {
            Clients.All.sendMessage(fid, message);
        }

        public void SendInit(int fireid)
        {
            string connectionId = Context.ConnectionId;
            var existConnection = fireConnection.Where(p => p.ConnectionId == connectionId).FirstOrDefault();
            if (existConnection == null)
            {
                fireConnection.Add(new FireConnection() { ConnectionId = connectionId, FireID = fireid });
            }
            else
            {
                if (existConnection.FireID == 0)
                {
                    existConnection.FireID = fireid;
                }
            }
        }

        public void SendOut()
        {
            string connectionId = Context.ConnectionId;
            var removeConnection = fireConnection.Where(p => p.ConnectionId == connectionId).FirstOrDefault();
            Log.Error("SendOut", "登出ID:" + connectionId);
            if (removeConnection != null)
            {
                fireConnection.Remove(removeConnection);
            }
        }

        
        /// <summary>
        /// 市局向区县询问
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="fireid"></param>
        /// <param name="message"></param>
        public  void  SendCityFireAsk(int userid, int fireid, string message)
        {

            string userName = string.Empty;
            //当前连接的connectionId
            string connectionId = Context.ConnectionId;
            var existConnection = fireConnection.Where(p => p.ConnectionId == connectionId).FirstOrDefault();
            if (existConnection == null)
            {
                fireConnection.Add(new FireConnection() { ConnectionId = connectionId, FireID = fireid });
            }
            else
            {
                if (existConnection.FireID == 0)
                {
                    existConnection.FireID = fireid;
                }
            }
            int askId = 0;
            try
            {
                userName = userinfoDAL.UsersInfosInfo(userid).UserName;
                //写入市局询问库
                F_CityFireAsk ask = new F_CityFireAsk();
                ask.CFA_TransUser = userid.ToString();
                ask.CFA_TransDatetime = DateTime.Now;
                ask.CFA_TransIP = CheckRequest.GetWebClientIp();
                ask.CFA_TransIP = ask.CFA_TransIP == null ? "0.0.0.0" : ask.CFA_TransIP;
                ask.CFA_HandleTime = ask.CFA_TransDatetime;
                ask.CFA_AskContent = message;
                ask.F_FireID = fireid;
                askId = dal.AddCityFireAsk(ask);

                //写入火灾信息表
                M_Record record = new M_Record();
                record.F_FireID = fireid;
                record.MR_HandleTime = ask.CFA_TransDatetime;
                record.MR_Type = (int)RecordType.市局询问;//市局询问 类型
                record.MR_UserID = 0;
                record.MR_Content = ask.CFA_AskContent;
                record.CFA_ID = askId;
                record.MR_AddTime = record.MR_HandleTime;
                record.MR_AddUser = userid.ToInt();
                record.MR_AddIP = ask.CFA_TransIP;
                record.MR_Applicant = userName;
                int recordId = dal.AddRecord(record);
               
                 
            
            }
            catch (Exception ex)
            {
                Log.Error("FireDisposalChatHub ", ex.ToString());
            }


            List<string> sendClients = fireConnection.Select(s => s.ConnectionId).ToList();
            //市局向区县发送询问消息
            Clients.Clients(sendClients).sendCountyMessage(userName, fireid, askId, message);
        }

        /// <summary>
        /// 区县向市局回复
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="fireid"></param>
        /// <param name="askid"></param>
        /// <param name="answername"></param>
        /// <param name="message"></param>
        public void SendCountyFireAnswer(int userid, int fireid, int askid,string answername, string message)
        {
            string userName = string.Empty;
            string askMessage = string.Empty;
            string answerMessage = message;
            string connectionId = Context.ConnectionId;
            var existConnection = fireConnection.Where(p => p.ConnectionId == connectionId).FirstOrDefault();
            if (existConnection == null)
            {
                fireConnection.Add(new FireConnection() { ConnectionId = connectionId, FireID = fireid });
            }
            else
            {
                if (existConnection.FireID == 0)
                {
                    existConnection.FireID = fireid;
                }
            }
            int answerId = 0;
            try
            {
                //校验市局询问
                var askInfo = dal.CityFireAskDetail(askid);
                askMessage=askInfo.CFA_AskContent;
                userName = userinfoDAL.UsersInfosInfo(userid).UserName;
                if (askInfo == null)
                {
                    return;
                }
                //判定是否回复过
                var existList = dal.ExistCountyFireAnswer(askid);
                
                //写入区县回复库
                F_CountyFireAnswer answer = new F_CountyFireAnswer();
                answer.F_FireID = fireid.ToInt();
                answer.CFA_ID = askid;
                answer.Cou_Answerer = answername;
                answer.Cou_AnswerContent = message;
                answer.Cou_TransDatetime = DateTime.Now;
                answer.Cou_HandleTime = answer.Cou_TransDatetime;
                answer.Cou_TransUser = userid.ToString();
                answer.Cou_TransIP = CheckRequest.GetWebClientIp() == null ? "0.0.0.0" : CheckRequest.GetWebClientIp();
                if (existList.Count == 0)
                {
                    answerId = dal.AddCountyFireAnswer(answer);
                }
                else
                {
                    var temp = existList.FirstOrDefault();
                    temp.Cou_AnswerContent = answer.Cou_AnswerContent;
                    temp.Cou_Answerer = answername;
                    temp.Cou_TransDatetime = answer.Cou_TransDatetime;
                    temp.Cou_HandleTime = answer.Cou_HandleTime;
                    temp.Cou_TransUser = answer.Cou_TransUser;
                    answerId= dal.UpdateCountyFireAnswer(temp);
                }
                if (existList.Count == 0)
                {
                    //写入火灾信息表
                    M_Record record = new M_Record();
                    record.F_FireID = fireid.ToInt();
                    record.MR_HandleTime = answer.Cou_TransDatetime;
                    record.MR_Type = (int)RecordType.区县回答;//区县回复 类型
                    record.MR_UserID = 0;
                    record.MR_Content = answer.Cou_AnswerContent;
                    record.CFA_ID = answer.CFA_ID;
                    record.MR_AddTime = askInfo.CFA_TransDatetime;//询问与问答排序
                    record.MR_AddUser = userid;
                    record.MR_AddIP = answer.Cou_TransIP;
                    record.MR_Applicant = answername;
                    int recordId = dal.AddRecord(record);
                }
            }
            catch (Exception ex)
            {
                Log.Error("FireDisposalChatHub ", ex.ToString());
            }
            List<string> sendClients = fireConnection.Select(s => s.ConnectionId).ToList();

            //区县向市局发送回复信息
            Clients.Clients(sendClients).sendCityMessage(userName, fireid, askid, answerId, answername, askMessage, answerMessage);
        }

        public override Task OnConnected()
        {
            string connectionId = Context.ConnectionId;
            var existConnection = fireConnection.Where(p => p.ConnectionId == connectionId).FirstOrDefault();
            if (existConnection == null)
            {
                fireConnection.Add(new FireConnection() { ConnectionId = connectionId });
            }
            return base.OnConnected();
        }


        public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
        {
            string connectionId = Context.ConnectionId;
            var removeConnection = fireConnection.Where(p => p.ConnectionId == connectionId).FirstOrDefault();
            if (removeConnection != null)
            {
                fireConnection.Remove(removeConnection);
            }
            return base.OnDisconnected(stopCalled);
        }
        public static List<FireConnection> fireConnection = new List<FireConnection>();

    }
}



